'use client';

import { useEffect, useRef, useState } from 'react';
import { FamilyMember } from '../types/family';
import { convertToAncientNumber, convertDateToAncient } from '../types/ancientNumberMap';
import { generatePDF } from '../utils/pdfGenerator';

// Import vis.js types and classes
import { Network } from 'vis-network';
import { DataSet } from 'vis-data';

interface TreeViewProps {
  familyData: FamilyMember[];
}

export default function TreeView({ familyData }: TreeViewProps) {
  const networkRef = useRef<HTMLDivElement>(null);
  const networkInstance = useRef<Network | null>(null);
  const [selectedNode, setSelectedNode] = useState<FamilyMember | null>(null);
  const [isMaximized, setIsMaximized] = useState(false);


  const formatDateRange = (birthDate: string, deathDate: string) => {
    const birth = birthDate ? convertDateToAncient(birthDate) : '?';
    const death = deathDate ? convertDateToAncient(deathDate) : '在世';
    return `${birth} - ${death}`;
  };

  // 最大化/还原功能
  const toggleMaximize = () => {
    setIsMaximized(!isMaximized);
    // 延迟一点时间让DOM更新后再调整网络视图
    setTimeout(() => {
      if (networkInstance.current) {
        networkInstance.current.fit();
      }
    }, 100);
  };



  // 下载PDF
  const downloadPDF = async () => {
    try {
      await generatePDF('treeview-content', {
        filename: '族谱关系图.pdf',
        orientation: 'landscape',
        format: 'a3'
      });
    } catch (error) {
      alert('PDF生成失败，请重试');
    }
  };

  useEffect(() => {
    if (!networkRef.current || familyData.length === 0) return;

    // 创建节点数据
    const nodes = familyData.map(person => {
      const isMale = (person.gender || 'male') === 'male';

      return {
        id: person.id,
        label: `${person.name}`,
        color: {
          background: isMale ? '#dbeafe' : '#fce7f3',
          border: isMale ? '#3b82f6' : '#ec4899',
          highlight: {
            background: isMale ? '#bfdbfe' : '#fbcfe8',
            border: isMale ? '#1d4ed8' : '#be185d'
          }
        },
        font: {
          color: isMale ? '#1e40af' : '#be185d',
          size: 30,
          face: 'Arial'
        },
        shape: 'box',
        margin: 10,
        widthConstraint: {
          minimum: 100,
          maximum: 150
        },
        heightConstraint: {
          minimum: 60
        },
        borderWidth: 2,
        borderWidthSelected: 3,
        level: person.generation,
        person: person
      };
    });

    // 创建边数据（父子关系）
    const edges = familyData
      .filter(person => person.parentId)
      .map(person => ({
        from: person.parentId!,
        to: person.id,
        arrows: 'to',
        color: {
          color: '#6b7280',
          highlight: '#374151'
        },
        width: 2,
        smooth: {
          type: 'cubicBezier',
          forceDirection: 'vertical',
          roundness: 0.4
        }
      }));

    // 创建DataSet
    const nodesDataSet = new DataSet(nodes);
    const edgesDataSet = new DataSet(edges);

    // 网络配置
    const options = {
      layout: {
        hierarchical: {
          direction: 'UD',
          sortMethod: 'directed',
          levelSeparation: 150,
          nodeSpacing: 200,
          treeSpacing: 250,
          blockShifting: true,
          edgeMinimization: true,
          parentCentralization: true,
          shakeTowards: 'roots'
        }
      },
      physics: {
        enabled: false
      },
      nodes: {
        chosen: true,
        shadow: {
          enabled: true,
          color: 'rgba(0,0,0,0.2)',
          size: 10,
          x: 2,
          y: 2
        }
      },
      edges: {
        chosen: true,
        shadow: {
          enabled: true,
          color: 'rgba(0,0,0,0.1)',
          size: 5,
          x: 1,
          y: 1
        }
      },
      interaction: {
        dragNodes: true,
        dragView: true,
        zoomView: true,
        selectConnectedEdges: false
      }
    };

    // 创建网络
    networkInstance.current = new Network(
      networkRef.current,
      { nodes: nodesDataSet, edges: edgesDataSet },
      options
    );

    // 添加点击事件
    networkInstance.current.on('click', (params) => {
      if (params.nodes.length > 0) {
        const nodeId = params.nodes[0];
        const person = familyData.find(p => p.id === nodeId);
        setSelectedNode(person || null);
      } else {
        setSelectedNode(null);
      }
    });

    // 清理函数
    return () => {
      if (networkInstance.current) {
        networkInstance.current.destroy();
        networkInstance.current = null;
      }
    };
  }, [familyData]);

  // 监听最大化状态变化，重新调整网络视图
  useEffect(() => {
    if (networkInstance.current) {
      setTimeout(() => {
        networkInstance.current?.fit();
      }, 200);
    }
  }, [isMaximized]);

  // 监听ESC键退出全屏
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && isMaximized) {
        setIsMaximized(false);
      }
    };

    if (isMaximized) {
      document.addEventListener('keydown', handleKeyDown);
      // 防止页面滚动
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = 'auto';
    };
  }, [isMaximized]);

  if (familyData.length === 0) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-500 text-lg">暂无族谱数据，请先添加成员</p>
      </div>
    );
  }

  return (
    <div className={`${isMaximized ? 'fixed inset-0 z-50 bg-white' : 'p-6 h-screen'} flex flex-col`}>
      <div className="flex justify-between items-center mb-4 p-6">
        <div className="flex items-center gap-4">

          <h2 className="text-2xl font-bold text-gray-800">
            家族关系图 - 可视化族谱世系图
          </h2>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => {
              if (networkInstance.current && networkRef.current) {
                // 模拟滚轮事件来实现缩放
                const event = new WheelEvent('wheel', {
                  deltaY: -100, // 负值表示向上滚动（放大）
                  bubbles: true,
                  cancelable: true
                });
                networkRef.current.dispatchEvent(event);
              }
            }}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center gap-1"
            title="放大族谱图"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            放大
          </button>
          <button
            onClick={() => {
              if (networkInstance.current && networkRef.current) {
                // 模拟滚轮事件来实现缩放
                const event = new WheelEvent('wheel', {
                  deltaY: 100, // 正值表示向下滚动（缩小）
                  bubbles: true,
                  cancelable: true
                });
                networkRef.current.dispatchEvent(event);
              }
            }}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center gap-1"
            title="缩小族谱图"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 12H6" />
            </svg>
            缩小
          </button>
          <button
            onClick={() => networkInstance.current?.fit()}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center gap-1"
            aria-label="调整族谱视图到最佳显示状态"
            title="自动调整族谱图到最佳显示比例"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            重置
          </button>
          <button
            onClick={toggleMaximize}
            className="px-3 py-1 text-sm bg-purple-500 text-white rounded hover:bg-purple-600 transition-colors flex items-center gap-1"
            title={isMaximized ? '还原窗口' : '最大化'}
          >
            {isMaximized ? (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                </svg>
                还原
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8l4-4m0 0h4m-4 0v4m12-4l-4 4m0 0v4m0-4h4m-8 8l-4-4m0 0v-4m0 4h-4m8 0l4 4m0 0v-4m0 4h-4" />
                </svg>
                最大化
              </>
            )}
          </button>
          <button
            onClick={downloadPDF}
            className="px-3 py-1 text-sm bg-green-500 text-white rounded hover:bg-green-600 transition-colors flex items-center gap-1"
            aria-label="导出族谱为PDF文档"
            title="将当前族谱关系图导出为高质量PDF文件"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            下载PDF
          </button>
        </div>
      </div>

      <div className={`flex flex-1 gap-4 ${isMaximized ? 'px-6' : ''}`}>
        {/* 网络图 */}
        <div className="flex-1 border border-gray-300 rounded-lg overflow-hidden">
          <div id="treeview-content" ref={networkRef} className="w-full h-full bg-white" />
        </div>

        {/* 详细信息面板 */}
        {selectedNode && (
          <div className={`${isMaximized ? 'w-96' : 'w-80'} bg-white border border-gray-300 rounded-lg p-4 overflow-y-auto`}>
            <h3 className="text-lg font-bold mb-4 text-center">
              <span className={`${(selectedNode.gender || 'male') === 'male' ? 'text-blue-600' : 'text-pink-600'}`}>
                {selectedNode.name}
              </span>
            </h3>

            <div className="space-y-3 text-sm">
              <div>
                <strong>性别:</strong> {(selectedNode.gender || 'male') === 'male' ? '男' : '女'}
              </div>

              <div>
                <strong>世次:</strong> 第{convertToAncientNumber(selectedNode.generation)}世
              </div>

              <div>
                <strong>何人子女:</strong> {
                  selectedNode.parentId
                    ? familyData.find(p => p.id === selectedNode.parentId)?.name || '无'
                    : '始祖'
                }
              </div>

              <div>
                <strong>排行:</strong> {selectedNode.ranking || '无'}
              </div>

              <div>
                <strong>生终年月:</strong> {formatDateRange(selectedNode.birthDate, selectedNode.deathDate)}
              </div>

              {selectedNode.biography && (
                <div>
                  <strong>履历:</strong> {selectedNode.biography}
                </div>
              )}

              <div>
                <strong>配偶:</strong>
                <span className={selectedNode.spouseName ? ((selectedNode.gender || 'male') === 'male' ? 'text-pink-600' : 'text-blue-600') : ''}>
                  {selectedNode.spouseName || '无'}
                </span>
              </div>

              {selectedNode.spouseName && (
                <div>
                  <strong>配偶生终年月:</strong> {formatDateRange(selectedNode.spouseBirthDate, selectedNode.spouseDeathDate)}
                </div>
              )}

              {selectedNode.spouseBiography && (
                <div>
                  <strong>配偶履历:</strong> {selectedNode.spouseBiography}
                </div>
              )}

              <div>
                <strong>现在住址:</strong> {selectedNode.town + selectedNode.county}
              </div>

              {selectedNode.notes && (
                <div>
                  <strong>备注:</strong> {selectedNode.notes}
                </div>
              )}

              <div>
                <strong>子女数量:</strong> {
                  familyData.filter(p => p.parentId === selectedNode.id).length
                }人
              </div>
            </div>
          </div>
        )}
      </div>

      <div className={`mt-4 text-sm text-gray-600 text-center ${isMaximized ? 'px-6 pb-6' : ''}`}>
        点击节点查看详细信息 | 拖拽移动视图 | 滚轮缩放 | 工具栏放大缩小 | {isMaximized ? '按ESC键或点击还原按钮退出全屏' : '点击最大化按钮进入全屏'}
      </div>
    </div>
  );
}